import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import { createPinia } from 'pinia'
import Toast from 'vue-toastification'
import 'vue-toastification/dist/index.css'

import App from './App.vue'
import './style.css'

// Import views
import Home from './views/Home.vue'
import StoryGenerator from './views/StoryGenerator.vue'
import StoryLibrary from './views/StoryLibrary.vue'
import StoryDetail from './views/StoryDetail.vue'
import Profile from './views/Profile.vue'
import Settings from './views/Settings.vue'
import Ranking from './views/Ranking.vue'

// Router configuration
const routes = [
  { path: '/', name: 'Home', component: Home },
  { path: '/generate', name: 'StoryGenerator', component: StoryGenerator },
  { path: '/library', name: 'StoryLibrary', component: StoryLibrary },
  { path: '/story/:id', name: 'StoryDetail', component: StoryDetail, props: true },
  { path: '/profile', name: 'Profile', component: Profile },
  { path: '/settings', name: 'Settings', component: Settings },
  { path: '/ranking', name: 'Ranking', component: Ranking },
  { path: '/admin', name: 'Admin', component: () => import('./views/Admin.vue') }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

const pinia = createPinia()

const app = createApp(App)

app.use(router)
app.use(pinia)
app.use(Toast, {
  position: 'top-right',
  timeout: 3000,
  closeOnClick: true,
  pauseOnFocusLoss: true,
  pauseOnHover: true,
  draggable: true,
  draggablePercent: 0.6,
  showCloseButtonOnHover: false,
  hideProgressBar: false,
  closeButton: 'button',
  icon: true,
  rtl: false
})

app.mount('#app')

// Initialize stores after app is mounted
import { useAuthStore } from './stores/auth.js'
import { useStoriesStore } from './stores/stories.js'

// 异步初始化认证和数据
;(async () => {
  try {
    // 初始化认证状态
    const authStore = useAuthStore()
    await authStore.initializeAuth()
    
    // 加载故事列表（从后端API）
    const storiesStore = useStoriesStore()
    await storiesStore.loadStories({
      status: 'published',
      page: 1,
      page_size: 20
    })
  } catch (error) {
    console.error('初始化失败:', error)
  }
})()
